package com.lc.mqtt.service;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson2.JSON;
import com.study.common.constant.MqttConstant;
import com.study.common.entity.dto.MqttMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/11/13 14:24
 */
@Slf4j
@Service
public class MqttMessageService {

    @Resource
    private MqttClient mqttClient;

    /**
     * 局部发送消息
     */
    public <T> void sendPartMessage(MqttMessageDto<T> dto){
        try {
            String jsonString = JSON.toJSONString(dto);
            log.info("主题：{}，发送mqtt消息：{}", MqttConstant.PART_TOPIC, jsonString);
            mqttClient.publish(MqttConstant.PART_TOPIC, jsonString.getBytes(), MqttConstant.QOS_0, false);
        } catch (MqttException e) {
            log.error("局部发送mqtt消息异常：{}", ExceptionUtil.stacktraceToString(e));
        }
    }

    /**
     * 全局发布消息
     */
    public <T> void sendGlobalMessage(MqttMessageDto<T> dto){
        try {
            String jsonString = JSON.toJSONString(dto);
            String globalTopic = MqttConstant.GLOBAL_TOPIC + MqttConstant.GLOBAL_SUFFIX;
            log.info("全局主题：{}，发送发送mqtt消息：{}", globalTopic, jsonString);
            mqttClient.publish(globalTopic, jsonString.getBytes(), MqttConstant.QOS_1, false);
        } catch (MqttException e) {
            log.error("全局发送mqtt消息异常：{}", ExceptionUtil.stacktraceToString(e));
        }
    }
}
